package net.qunzhi.modules.weixin.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.qunzhi.common.utils.Constant;
import net.qunzhi.modules.cms.entity.TbUserInfoEntity;
import net.qunzhi.modules.cms.service.TbUserInfoService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 用户关注事件处理器
 * <p>
 * Created by lsd
 * 2019-09-02 10:54
 */
@Slf4j
@Component
public class SubscribeHandler implements WxMpMessageHandler {
    @Autowired
    private TbUserInfoService tbUserInfoService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        log.info("新关注用户 OPENID: " + wxMessage.getFromUser());
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = wxMpService.getUserService().userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // TODO 可以添加关注用户到本地数据库
                String openId = userWxInfo.getOpenId();
                TbUserInfoEntity one = tbUserInfoService.getOne(
                        new QueryWrapper<TbUserInfoEntity>().lambda().eq(TbUserInfoEntity::getOpenId, openId));
                // 4 若用户不存在则保存到tb_user_info，默认未激活
                if (one == null) {
                    TbUserInfoEntity userEntity = new TbUserInfoEntity();
                    userEntity.setOpenId(openId);
                    userEntity.setStatus(Constant.ONE);
                    //用户名和头像都可以通过这个信息获取
                    userEntity.setUsername(userWxInfo.getNickname());
                    userEntity.setAvatar(userWxInfo.getHeadImgUrl());
                    tbUserInfoService.save(userEntity);
                }
            }
        } catch (WxErrorException e) {
            log.error("获取微信用户基本信息失败！{}",e.getMessage());
            if (e.getError().getErrorCode() == 48001) {
                log.error("该公众号没有获取用户信息权限！");
            }
            try {
                return WxMpXmlOutMessage.TEXT()
                        .content("很抱歉，获取微信用户基本信息失败，请取消关注后再试")
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser())
                        .build();
            } catch (Exception ex) {
                log.error("关注后推送信息失败，{}", ex.getMessage());
                return null;
            }
        }

        try {
            return WxMpXmlOutMessage.TEXT()
                    .content("感谢关注")
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .build();
        } catch (Exception e) {
            log.error("关注后推送信息失败，{}", e.getMessage());
            return null;
        }
    }
}
